import React, { useState, useEffect } from 'react';
import {
  Tree, Button, Space, Modal, Form, Input, Select, message,
  Card, Row, Col, Typography, Tag, Popconfirm, Drawer, Avatar,
  Table, Tabs, Divider, Tooltip, Badge, Switch, InputNumber
} from 'antd';
import {
  PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined,
  TeamOutlined, UserOutlined, SettingOutlined, ReloadOutlined,
  SearchOutlined, ExportOutlined, ImportOutlined, BranchesOutlined,
  CrownOutlined, UsergroupAddOutlined, KeyOutlined, BarChartOutlined
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';
import {
  organizationService,
  Department,
  DepartmentMember,
  CreateDepartmentRequest,
  UpdateDepartmentRequest,
  DepartmentMemberAssignment
} from '@/services/organizationService';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

interface OrganizationState {
  departments: Department[];
  departmentTree: DataNode[];
  selectedDepartment: Department | null;
  departmentMembers: DepartmentMember[];
  loading: boolean;
  membersLoading: boolean;
  editingDepartment: Department | null;
  modalVisible: boolean;
  memberModalVisible: boolean;
  detailVisible: boolean;
  expandedKeys: string[];
  selectedKeys: string[];
}

export default function OrganizationManagement() {
  const [state, setState] = useState<OrganizationState>({
    departments: [],
    departmentTree: [],
    selectedDepartment: null,
    departmentMembers: [],
    loading: false,
    membersLoading: false,
    editingDepartment: null,
    modalVisible: false,
    memberModalVisible: false,
    detailVisible: false,
    expandedKeys: [],
    selectedKeys: []
  });

  const [form] = Form.useForm();
  const [memberForm] = Form.useForm();
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statistics, setStatistics] = useState<any>(null);

  // 加载部门树
  const loadDepartmentTree = async () => {
    setState(prev => ({ ...prev, loading: true }));
    
    try {
      const departments = await organizationService.getDepartmentTree();
      const treeData = buildTreeData(departments);
      
      setState(prev => ({
        ...prev,
        departments,
        departmentTree: treeData,
        loading: false
      }));
    } catch (error: any) {
      console.error('加载部门树失败:', error);
      message.error('加载部门树失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 构建树形数据
  const buildTreeData = (departments: Department[]): DataNode[] => {
    return departments.map(dept => ({
      key: dept.id,
      title: (
        <div className="flex items-center justify-between">
          <Space>
            <TeamOutlined />
            <span>{dept.name}</span>
            <Text type="secondary">({dept.memberCount})</Text>
            {dept.managerId && <CrownOutlined style={{ color: '#faad14' }} />}
          </Space>
          <Space>
            <Tag color={dept.status === 'active' ? 'green' : 'red'}>
              {dept.status === 'active' ? '正常' : '禁用'}
            </Tag>
          </Space>
        </div>
      ),
      children: dept.children ? buildTreeData(dept.children) : undefined,
      isLeaf: dept.childCount === 0
    }));
  };

  // 加载部门成员
  const loadDepartmentMembers = async (departmentId: string) => {
    setState(prev => ({ ...prev, membersLoading: true }));
    
    try {
      const response = await organizationService.getDepartmentMembers(departmentId, {
        includeSubDepartments: false,
        page: 0,
        size: 100
      });
      
      setState(prev => ({
        ...prev,
        departmentMembers: response.content,
        membersLoading: false
      }));
    } catch (error: any) {
      console.error('加载部门成员失败:', error);
      message.error('加载部门成员失败');
      setState(prev => ({ ...prev, membersLoading: false }));
    }
  };

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      const stats = await organizationService.getDepartmentStatistics();
      setStatistics(stats);
    } catch (error: any) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 初始化
  useEffect(() => {
    loadDepartmentTree();
    loadStatistics();
  }, []);

  // 选择部门
  const handleSelectDepartment = async (selectedKeys: React.Key[]) => {
    if (selectedKeys.length === 0) {
      setState(prev => ({
        ...prev,
        selectedDepartment: null,
        departmentMembers: [],
        selectedKeys: []
      }));
      return;
    }

    const departmentId = selectedKeys[0] as string;
    const department = findDepartmentById(state.departments, departmentId);
    
    if (department) {
      setState(prev => ({
        ...prev,
        selectedDepartment: department,
        selectedKeys: [departmentId]
      }));
      
      await loadDepartmentMembers(departmentId);
    }
  };

  // 查找部门
  const findDepartmentById = (departments: Department[], id: string): Department | null => {
    for (const dept of departments) {
      if (dept.id === id) return dept;
      if (dept.children) {
        const found = findDepartmentById(dept.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  // 创建/编辑部门
  const handleSaveDepartment = async (values: any) => {
    try {
      if (state.editingDepartment) {
        await organizationService.updateDepartment(state.editingDepartment.id, values);
        message.success('部门更新成功');
      } else {
        await organizationService.createDepartment(values);
        message.success('部门创建成功');
      }

      setState(prev => ({
        ...prev,
        modalVisible: false,
        editingDepartment: null
      }));
      form.resetFields();
      loadDepartmentTree();
      loadStatistics();
    } catch (error: any) {
      console.error('保存部门失败:', error);
      message.error('保存部门失败');
    }
  };

  // 删除部门
  const handleDeleteDepartment = async (department: Department) => {
    try {
      await organizationService.deleteDepartment(department.id);
      message.success('部门删除成功');
      loadDepartmentTree();
      loadStatistics();
      
      if (state.selectedDepartment?.id === department.id) {
        setState(prev => ({
          ...prev,
          selectedDepartment: null,
          departmentMembers: [],
          selectedKeys: []
        }));
      }
    } catch (error: any) {
      console.error('删除部门失败:', error);
      message.error('删除部门失败');
    }
  };

  // 添加部门成员
  const handleAddMember = async (values: any) => {
    if (!state.selectedDepartment) return;

    try {
      const members: DepartmentMemberAssignment[] = [{
        userId: values.userId,
        position: values.position,
        isManager: values.isManager || false,
        isPrimary: values.isPrimary || false,
        roles: values.roles || []
      }];

      await organizationService.addDepartmentMembers(state.selectedDepartment.id, members);
      message.success('成员添加成功');
      
      setState(prev => ({ ...prev, memberModalVisible: false }));
      memberForm.resetFields();
      loadDepartmentMembers(state.selectedDepartment.id);
      loadDepartmentTree();
    } catch (error: any) {
      console.error('添加成员失败:', error);
      message.error('添加成员失败');
    }
  };

  // 移除部门成员
  const handleRemoveMember = async (userId: string) => {
    if (!state.selectedDepartment) return;

    try {
      await organizationService.removeDepartmentMembers(state.selectedDepartment.id, [userId]);
      message.success('成员移除成功');
      loadDepartmentMembers(state.selectedDepartment.id);
      loadDepartmentTree();
    } catch (error: any) {
      console.error('移除成员失败:', error);
      message.error('移除成员失败');
    }
  };

  // 设置部门负责人
  const handleSetManager = async (userId: string) => {
    if (!state.selectedDepartment) return;

    try {
      await organizationService.setDepartmentManager(state.selectedDepartment.id, userId);
      message.success('负责人设置成功');
      loadDepartmentMembers(state.selectedDepartment.id);
      loadDepartmentTree();
    } catch (error: any) {
      console.error('设置负责人失败:', error);
      message.error('设置负责人失败');
    }
  };

  // 搜索部门
  const handleSearch = async (keyword: string) => {
    setSearchKeyword(keyword);
    if (!keyword.trim()) {
      loadDepartmentTree();
      return;
    }

    try {
      const results = await organizationService.searchDepartments(keyword, {
        maxResults: 50
      });
      
      const treeData = buildTreeData(results);
      setState(prev => ({ ...prev, departmentTree: treeData }));
    } catch (error: any) {
      console.error('搜索部门失败:', error);
      message.error('搜索部门失败');
    }
  };

  // 导出组织架构
  const handleExport = async () => {
    try {
      const blob = await organizationService.exportOrganization({
        format: 'excel',
        includeMembers: true,
        includeStatistics: true
      });
      
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `organization-${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  // 成员表格列定义
  const memberColumns: ColumnsType<DepartmentMember> = [
    {
      title: '成员',
      key: 'member',
      render: (_, record: DepartmentMember) => (
        <Space>
          <Avatar 
            src={record.avatar} 
            icon={<UserOutlined />}
            size="small"
          />
          <div>
            <div>{record.displayName}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              @{record.username}
            </Text>
          </div>
        </Space>
      )
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      render: (position: string) => position || '-'
    },
    {
      title: '角色',
      key: 'role',
      render: (_, record: DepartmentMember) => (
        <Space>
          {record.isManager && <Tag color="gold">负责人</Tag>}
          {record.isPrimary && <Tag color="blue">主要部门</Tag>}
          <Tag color={record.status === 'active' ? 'green' : 'red'}>
            {record.status === 'active' ? '正常' : '禁用'}
          </Tag>
        </Space>
      )
    },
    {
      title: '加入时间',
      dataIndex: 'joinedAt',
      key: 'joinedAt',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: DepartmentMember) => (
        <Space>
          {!record.isManager && (
            <Tooltip title="设为负责人">
              <Button
                type="text"
                size="small"
                icon={<CrownOutlined />}
                onClick={() => handleSetManager(record.userId)}
              />
            </Tooltip>
          )}
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => message.info('编辑成员功能开发中...')}
            />
          </Tooltip>
          <Popconfirm
            title="确定要移除这个成员吗？"
            onConfirm={() => handleRemoveMember(record.userId)}
          >
            <Tooltip title="移除">
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <Title level={2}>组织架构管理</Title>
        <Text type="secondary">管理企业组织架构、部门和人员分配</Text>
      </div>

      {/* 统计卡片 */}
      {statistics && (
        <Row gutter={16} className="mb-6">
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{statistics.totalMembers}</div>
                <div className="text-gray-500">总人数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{statistics.activeMembers}</div>
                <div className="text-gray-500">在职人数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-600">{statistics.subDepartments}</div>
                <div className="text-gray-500">部门数量</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600">{statistics.managers}</div>
                <div className="text-gray-500">管理人员</div>
              </div>
            </Card>
          </Col>
        </Row>
      )}

      <Row gutter={16}>
        {/* 左侧部门树 */}
        <Col span={8}>
          <Card 
            title="组织架构" 
            extra={
              <Space>
                <Tooltip title="新建部门">
                  <Button
                    type="text"
                    size="small"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      setState(prev => ({
                        ...prev,
                        editingDepartment: null,
                        modalVisible: true
                      }));
                      form.resetFields();
                      if (state.selectedDepartment) {
                        form.setFieldValue('parentId', state.selectedDepartment.id);
                      }
                    }}
                  />
                </Tooltip>
                <Tooltip title="刷新">
                  <Button
                    type="text"
                    size="small"
                    icon={<ReloadOutlined />}
                    onClick={loadDepartmentTree}
                  />
                </Tooltip>
                <Tooltip title="导出">
                  <Button
                    type="text"
                    size="small"
                    icon={<ExportOutlined />}
                    onClick={handleExport}
                  />
                </Tooltip>
              </Space>
            }
            bodyStyle={{ padding: '12px' }}
          >
            <div className="mb-3">
              <Search
                placeholder="搜索部门..."
                allowClear
                onSearch={handleSearch}
                style={{ width: '100%' }}
              />
            </div>
            
            {state.loading ? (
              <div className="text-center py-8">加载中...</div>
            ) : (
              <Tree
                treeData={state.departmentTree}
                expandedKeys={state.expandedKeys}
                selectedKeys={state.selectedKeys}
                onExpand={(expandedKeys) => {
                  setState(prev => ({ ...prev, expandedKeys: expandedKeys as string[] }));
                }}
                onSelect={handleSelectDepartment}
                showLine
                showIcon={false}
                height={600}
              />
            )}
          </Card>
        </Col>

        {/* 右侧详情 */}
        <Col span={16}>
          {state.selectedDepartment ? (
            <Card
              title={
                <Space>
                  <TeamOutlined />
                  <span>{state.selectedDepartment.name}</span>
                  <Tag color={state.selectedDepartment.status === 'active' ? 'green' : 'red'}>
                    {state.selectedDepartment.status === 'active' ? '正常' : '禁用'}
                  </Tag>
                </Space>
              }
              extra={
                <Space>
                  <Button
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => {
                      setState(prev => ({
                        ...prev,
                        editingDepartment: state.selectedDepartment,
                        modalVisible: true
                      }));
                      form.setFieldsValue(state.selectedDepartment);
                    }}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    title="确定要删除这个部门吗？"
                    onConfirm={() => handleDeleteDepartment(state.selectedDepartment!)}
                  >
                    <Button size="small" danger icon={<DeleteOutlined />}>
                      删除
                    </Button>
                  </Popconfirm>
                </Space>
              }
            >
              <Tabs defaultActiveKey="members">
                <TabPane tab={`成员 (${state.departmentMembers.length})`} key="members">
                  <div className="mb-4">
                    <Button
                      type="primary"
                      icon={<UsergroupAddOutlined />}
                      onClick={() => {
                        setState(prev => ({ ...prev, memberModalVisible: true }));
                        memberForm.resetFields();
                      }}
                    >
                      添加成员
                    </Button>
                  </div>
                  
                  <Table
                    columns={memberColumns}
                    dataSource={state.departmentMembers}
                    loading={state.membersLoading}
                    rowKey="userId"
                    size="small"
                    pagination={false}
                  />
                </TabPane>

                <TabPane tab="基本信息" key="info">
                  <div className="space-y-4">
                    <div>
                      <Text strong>部门代码：</Text>
                      <Text>{state.selectedDepartment.code}</Text>
                    </div>
                    
                    {state.selectedDepartment.description && (
                      <div>
                        <Text strong>部门描述：</Text>
                        <Text>{state.selectedDepartment.description}</Text>
                      </div>
                    )}
                    
                    <div>
                      <Text strong>部门层级：</Text>
                      <Text>{state.selectedDepartment.level}</Text>
                    </div>
                    
                    <div>
                      <Text strong>完整路径：</Text>
                      <Text>{state.selectedDepartment.fullPath}</Text>
                    </div>
                    
                    {state.selectedDepartment.managerName && (
                      <div>
                        <Text strong>部门负责人：</Text>
                        <Text>{state.selectedDepartment.managerName}</Text>
                      </div>
                    )}
                    
                    <div>
                      <Text strong>成员数量：</Text>
                      <Text>{state.selectedDepartment.memberCount}</Text>
                    </div>
                    
                    <div>
                      <Text strong>子部门数量：</Text>
                      <Text>{state.selectedDepartment.childCount}</Text>
                    </div>
                    
                    <div>
                      <Text strong>创建时间：</Text>
                      <Text>{new Date(state.selectedDepartment.createdAt).toLocaleString()}</Text>
                    </div>
                  </div>
                </TabPane>

                <TabPane tab="权限设置" key="permissions">
                  <div>
                    <Text type="secondary">权限管理功能开发中...</Text>
                  </div>
                </TabPane>
              </Tabs>
            </Card>
          ) : (
            <Card>
              <div className="text-center py-20">
                <BranchesOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                <div className="mt-4 text-gray-500">请选择一个部门查看详情</div>
              </div>
            </Card>
          )}
        </Col>
      </Row>

      {/* 创建/编辑部门模态框 */}
      <Modal
        title={state.editingDepartment ? '编辑部门' : '新建部门'}
        open={state.modalVisible}
        onCancel={() => {
          setState(prev => ({
            ...prev,
            modalVisible: false,
            editingDepartment: null
          }));
          form.resetFields();
        }}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveDepartment}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="部门名称"
                rules={[{ required: true, message: '请输入部门名称' }]}
              >
                <Input placeholder="请输入部门名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="部门代码"
                rules={[{ required: true, message: '请输入部门代码' }]}
              >
                <Input placeholder="请输入部门代码" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="部门描述"
          >
            <TextArea rows={3} placeholder="请输入部门描述" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="parentId"
                label="上级部门"
              >
                <Select placeholder="请选择上级部门" allowClear>
                  {/* 这里应该渲染部门选项 */}
                  <Option value="">无上级部门</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="sortOrder"
                label="排序"
                initialValue={0}
              >
                <InputNumber min={0} placeholder="排序" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 添加成员模态框 */}
      <Modal
        title="添加部门成员"
        open={state.memberModalVisible}
        onCancel={() => {
          setState(prev => ({ ...prev, memberModalVisible: false }));
          memberForm.resetFields();
        }}
        onOk={() => memberForm.submit()}
      >
        <Form
          form={memberForm}
          layout="vertical"
          onFinish={handleAddMember}
        >
          <Form.Item
            name="userId"
            label="选择用户"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select placeholder="请选择用户" showSearch>
              {/* 这里应该渲染用户选项 */}
            </Select>
          </Form.Item>

          <Form.Item
            name="position"
            label="职位"
          >
            <Input placeholder="请输入职位" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="isManager"
                label="设为负责人"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="isPrimary"
                label="主要部门"
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}